import pyautogui
import time
import random
import logging
import keyboard
from typing import Optional, Tuple
# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 安全设置：设置故障安全（将鼠标移动到左上角会触发异常停止）
pyautogui.FAILSAFE = True
# 设置每次操作后的暂停时间（秒）
pyautogui.PAUSE = 0.5


def getMouseXY(
        left: str = 'f8',
        right: str = 'f9',
        exit_hotkey: str = 'esc',
        show_help: bool = True
) -> Optional[Tuple[int, int]]:
    """
    通过快捷键交互式获取鼠标坐标
    :param left: 捕获坐标的热键（默认F8）
    :param exit_hotkey: 退出程序的热键（默认ESC）
    :param show_help: 是否显示操作提示
    :return: 最后捕获的(x, y)坐标或None
    """
    captured_pos = None

    if show_help:
        print("\n=== 鼠标坐标捕获模式 ===")
        print(f"按下 [{left.upper()}] 左键")
        print(f"按下 [{right.upper()}] 右键")
        print(f"按下 [{exit_hotkey.upper()}] 退出捕获模式")
        print("=====================\n")

    try:
        while True:
            if keyboard.is_pressed(left):
                x, y = pyautogui.position()
                captured_pos = (x, y)
                print(f"func.leftClick(x={x}, y={y})")
                # 等待按键释放避免重复触发
                while keyboard.is_pressed(left):
                    time.sleep(0.1)
            if keyboard.is_pressed(right):
                x, y = pyautogui.position()
                captured_pos = (x, y)
                # logger.info(f"func.rightClick(x={x}, y={y})")
                print(f"func.rightClick(x={x}, y={y})")
                # 等待按键释放避免重复触发
                while keyboard.is_pressed(left):
                    time.sleep(0.1)
            if keyboard.is_pressed(exit_hotkey):
                logger.info("退出坐标捕获模式")
                break

            time.sleep(0.05)  # 降低CPU占用

    except Exception as e:
        logger.error(f"捕获坐标时出错: {str(e)}")
    finally:
        return captured_pos


def leftClick(x=None, y=None, clicks=1, interval=0.1):
    """
    模拟鼠标左键点击
    :param x: 目标X坐标（None表示当前位置）
    :param y: 目标Y坐标（None表示当前位置）
    :param clicks: 点击次数
    :param interval: 多次点击之间的间隔(秒)
    """
    try:
        if x is None and y is None:
            x, y = pyautogui.position()
        pyautogui.moveTo(x, y, duration=random.uniform(0.1, 0.3))
        pyautogui.click(button='left', clicks=clicks, interval=interval)
        logger.info(f"在 ({x if x else '当前X'}, {y if y else '当前Y'}) 位置左键点击{clicks}次")
        delay(0.2,0.5)
    except Exception as e:
        logger.error(f"点击操作失败: {str(e)}")
def rightClick(x=None, y=None, clicks=1, interval=0.1):
    """
    模拟鼠标左键点击
    :param x: 目标X坐标（None表示当前位置）
    :param y: 目标Y坐标（None表示当前位置）
    :param clicks: 点击次数
    :param interval: 多次点击之间的间隔(秒)
    """
    try:
        if x is None and y is None:
            x, y = pyautogui.position()
        pyautogui.moveTo(x, y, duration=random.uniform(0.1, 0.3))

        pyautogui.click(button='right', clicks=clicks, interval=interval)
        logger.info(f"在 ({x if x else '当前X'}, {y if y else '当前Y'}) 位置右键点击{clicks}次")
        delay(0.2, 0.5)
    except Exception as e:
        logger.error(f"点击操作失败: {str(e)}")

def keypress(key: str, presses: int = 1, interval: float = 0.1) -> None:
    """
    模拟按键操作

    :param key: 要按的键
    :param presses: 按键次数 (默认1次)
    :param interval: 按键间隔 (秒)
    """
    try:
        for _ in range(presses):
            keyboard.press(key)
            time.sleep(0.05)  # 短暂按下
            keyboard.release(key)
            time.sleep(interval)
    except Exception as e:
        logging.error(f"按键 {key} 失败: {str(e)}")
def delay(min_sec=0.5, max_sec=1.0):
    """
    随机延时（模拟人类操作间隔）
    :param min_sec: 最小延时(秒)
    :param max_sec: 最大延时(秒)
    """
    sleep_time = random.uniform(min_sec, max_sec)
    logger.debug(f"随机延时: {sleep_time:.2f}秒")
    time.sleep(sleep_time)

#
# # 示例用法
# if __name__ == "__main__":
#     # 示例1：获取鼠标坐标
#     final_pos = getMouseXY(duration=2)
#     print(f"最终坐标位置: {final_pos}")
#
#     # 示例2：在随机位置点击
#     if final_pos:
#         leftClick(*final_pos)
#
#     # 示例3：随机延时后点击屏幕中心
#     randSleep()
#     screen_width, screen_height = pyautogui.size()
#     leftClick(screen_width // 2, screen_height // 2)